export async function importHtml(entry) {
  let content = await loadSource(entry) // 1. 加载子应用入口
  const scripts = await pasrseScript(content, entry) // 2. 解析script
  const { styles, css} = await pasrseCss(content, entry) // 3. 解析css
  const body = pasrseBody(content) // 4. 解析body
  console.log({
    styles,
    css,
    scripts,
    body
  })
}
const ATTR_RE = /["'=\w\s]*/.source
/**
 * loadSource资源加载
 * @param url 
 * @returns 代码字符串
 */
function loadSource(url) {
  return window.fetch(url).then(res => res.text())
}
/**
 * pasrseScript 解析script
 * @param content html字符串 entry域名
 */
async function pasrseScript(content, entry) {
  // 1. 远程js用的时候在load， 也可以parse之后直接load进来，纯文本
  const SCRIPT_CONTENT_RE = new RegExp('<script'+ ATTR_RE + '>([\\w\\W]*)<\/script>', 'g')
  const SCRIPT_SRC_RE = new RegExp('<script'+ ATTR_RE + 'src="(.+)"><\/script>', 'g')
  let scripts = []
  let scriptsUrls = []
  let match
  while (match = SCRIPT_CONTENT_RE.exec(content)) {
    const script = match[1].trim()
    script && scripts.push(script)
  }
  while (match = SCRIPT_SRC_RE.exec(content)) {
    const url = match[1].trim()
    url && scriptsUrls.push(url)
  }
  let remoteScript = await Promise.all(scriptsUrls.map(url => {
    let u = (url.startsWith('http') ||  url.startsWith('https')) ? url: entry + url
    return loadSource(u)
  }))
  scripts = remoteScript.concat(scripts)
  return scripts
}
/**
 * pasrseScript 解析script
 * @param content html字符串 entry域名
 */
 async function pasrseCss(content, entry) { 
  const CSS_LINK_RE = new RegExp('<link'+ ATTR_RE + 'href="([^"]+.css[^"]*)"' + ATTR_RE +'>', 'g')
  const STYLE_CONTENT_RE = new RegExp('<style>([^<]*)<\/style>', 'g')
  const CSS_RE = new RegExp('(?:' + CSS_LINK_RE.source +')|(?:' + STYLE_CONTENT_RE.source + ')','g')
  let match
  let css = []
  let styles = []
  while (match = CSS_RE.exec(content)) {
    let style
    if(match[1]) {
      style = match[1].trim()
      style && css.push(style)
    } else if(match[2]) {
      style = match[2].trim()
      style && styles.push(style)
    }
  }
  return {
    css,
    styles
  }
}

/**
 * pasrseScript 解析body
 * @param content html字符串 entry域名
 */
 function pasrseBody(content, entry) { 
  const BODY_RE = new RegExp('<body>([\\w\\W])*<\/body>', 'g')
  const SCRIPT_CONTENT_RE = new RegExp('<script'+ ATTR_RE + '>([\\w\\W]*)<\/script>', 'g')
  const SCRIPT_SRC_RE = new RegExp('<script'+ ATTR_RE + 'src="(.+)"><\/script>', 'g')
  let bodyCotent = content.match(BODY_RE)
  if(bodyCotent && bodyCotent[0]) {
    bodyCotent = bodyCotent[0].replace(SCRIPT_CONTENT_RE, '').replace(SCRIPT_SRC_RE, '')
  }
  return bodyCotent
 }
